package com.qing.emailservice.service.impl;

import com.qing.emailservice.service.SendEmailService;
import com.qing.emailservice.common.utils.RedisUtil;
import com.qing.servicebase.exception.JsonException;
import com.qing.servicebase.utils.CheckTool;
import com.qing.servicebase.utils.ResponseResult;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Random;

/**
 * @ClassName Yjx
 * @Description TODO
 * @date 2022/9/14 20:22
 * @Version 1.0
 */
@Service
public class SendEmailServiceImpl implements SendEmailService {

    @Value("${spring.mail.username}")
    private String sender;
    private final JavaMailSender javaMailSender;
    @Resource
    private RedisUtil redisUtil;

    public SendEmailServiceImpl(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Async
    @Override
    public ResponseResult sendEmailCaptcha(String email) {
        //校验邮箱
        if (!CheckTool.isEmail(email.trim())) {
            return ResponseResult.ofException(new JsonException(201,"操作失败"));
        }

        // 构建一个邮件对象
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            String title = "";
            String tip = "";
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            // 设置邮件发送者，这个跟application.yml中设置的要一致
            helper.setFrom(sender);
            // 发送给 email
            helper.setTo(email.trim());
            helper.setSentDate(new Date());
            //随机生成功 6位 验证码
            Random random = new Random();
            int temp = random.nextInt(999999);
            String code = String.valueOf(temp > 100000 ? temp : temp + 100000);
            String key="register" + email.trim();
            redisUtil.set(key, code, 60 * 10);
            // 设置邮件主题
            helper.setSubject(title);
            // 设置邮件的正文
            helper.setText(buildContent(code, tip), true);
            // 发送邮件
            javaMailSender.send(message);
            return ResponseResult.ofSuccess("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.ofSuccess("发送成功");
    }

    /**
     * html 邮件内容
     *
     * @param code 验证码
     * @param tip  提示  ： 注册，重置
     * @return
     * @throws IOException
     */
    private String buildContent(String code, String tip) throws IOException {

        //加载邮件html模板
        String fileName = "static/email-model.html";
        InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName);
        BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            throw new JsonException(201,"操作失败");
        } finally {
            inputStream.close();
            fileReader.close();
        }

        String contentText = "验证码为：<span style='color: red '>" + code + "</span> ，有效时长为：10分钟。<br>The verification code is:" + code + ", and the valid time is: 10 minutes. ";


        //绿色
        String emailHeadColor = "#10fa81";
        String date = DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss");
        //填充html模板中的五个参数
        String htmlText = MessageFormat.format(buffer.toString(), emailHeadColor, tip, contentText, date);
        return htmlText;
    }

}
